import { OneModal } from '@/components/one-ui';
import { ContractManageAPI } from '../common/type';
import { IOneModalRef } from '@/pages/type';
import { ChangeEvent, Ref, useContext, useEffect, useRef, useState } from 'react';
import { AutoComplete, Card, Col, Empty, Input, Radio, Row, Spin, Tree, message } from 'antd';
import { ConractControllerContext } from '../common';
import { SearchOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import { clickScrollToAnchor, commonDeptGetUser, getDeptPosTreeIcon, loopArray, onCloseModalCommon, searchChangeColor, transltateFn } from '@/utils';

export const OpenDepartmentModal: React.FC<ContractManageAPI.IOpenDepartmentModal> = ({ onClose, checkTypeInfo }) => {
  /** 弹框高度样式 */
  const modalBodyStyle: React.CSSProperties = {
    height: document.body.clientHeight * 0.55,
    padding: 0,
  };

  /** 获取上下文 */
  const { contractForm, contractDetailInfo } = useContext(ConractControllerContext);

  /**弹框的ref*/
  const departmentRef: Ref<IOneModalRef> = useRef(null);

  /** 引入上下文 */
  const { styleFixCls } = useContext(ConractControllerContext);

  /** 左侧树 */
  const [leftTreeInfo, setLeftTreeInfo] = useState<Record<string, any>>({
    searchValueLeft: '',
    autoExpandParentLeft: false,
    expandedKeysLeft: [],
    selectKeysLeft: [],
    selectNodeInfo: {},
  });

  /** 右侧用户数据 */
  const [rightUserInfo, setRightUserInfo] = useState<Record<string, any>>({
    searchValueRight: '',
    selectRadioInfo: {},
  });

  /** 获取组织结构数据 */
  const { getFlowOrgTreeRun, getFlowOrgList, getFlowOrgTreeLoading } = getFlowOrgTreeByOrgIDService();
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 初始化获取组织机构树 */
  useEffect(() => {
    let deptParams = {
      params: 0,
      flowType: 'null',
    };
    getFlowOrgTreeRun(deptParams);
  }, []);

  // useEffect(() => {
  //   if (contractDetailInfo?.dutyerID) {
  //     const dutyInfo: Record<string, any> = contractForm?.getFieldsValue()?.dutyerID
  //       ? contractForm?.getFieldsValue()
  //       : contractDetailInfo;

  //     const selectDeptInfo: Record<string, any> = {
  //       attributes: {
  //         companyID: dutyInfo?.dutyCompanyID,
  //         companyName: dutyInfo?.dutyCompanyName,
  //         departmentID: dutyInfo?.dutyDepartmentID,
  //         departmentName: dutyInfo?.dutyDepartmentName,
  //       },
  //       id: dutyInfo?.dutyPositionID,
  //       text: dutyInfo?.dutyPositionName,
  //       textType: '2',
  //     };

  //     getUserRun([selectDeptInfo]);

  //     setLeftTreeInfo((prev: Record<string, any>) => {
  //       return {
  //         ...prev,
  //         selectNodeInfo: selectDeptInfo,
  //         selectKeysLeft: [dutyInfo?.dutyPositionID],
  //       };
  //     });

  //     const selectUserInfo: Record<string, any> = {
  //       id: dutyInfo?.dutyerID,
  //       realName: dutyInfo?.dutyerName,
  //       phoneMobile: dutyInfo?.dutyPhone,
  //     };
  //     setRightUserInfo((prev: Record<string, any>) => {
  //       return {
  //         ...prev,
  //         selectRadioInfo: selectUserInfo,
  //       };
  //     });
  //   }
  // }, [contractDetailInfo]);

  /** 搜索下拉菜单 */
  const autoOptionLeft = (dataList: Record<string, any>[], autoType: boolean) => {
    let option: Record<string, any>[] = [];
    const searchValue: string = autoType ? leftTreeInfo?.searchValueLeft : rightUserInfo?.searchValueRight;
    const dataName: string = autoType ? 'text' : 'realName';

    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if (!searchValue) {
          option.push({
            value: item?.[dataName],
            key: item?.id,
            itemrowobj: { ...item },
          });
        } else if (item?.[dataName]?.includes(searchValue)) {
          option.push({
            value: item?.[dataName],
            key: item?.id,
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(dataList);
    return option;
  };

  /** 左侧树搜索值改变  */
  const onSelectAuto = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    const rowObj = option?.itemrowobj;
    const targetNode = loopArray(getFlowOrgList); //平铺的树
    let openTreeIds = transltateFn(targetNode, rowObj?.pID);

    setLeftTreeInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        searchValueLeft: value,
        autoExpandParentLeft: true,
        expandedKeysLeft: openTreeIds,
      };
    });

    setTimeout(() => {
      clickScrollToAnchor(optionId + 'department');
    }, 1000);
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>, searchType: string) => {
    const inputValue: string = e.target.value;
    if (searchType == 'left') {
      setLeftTreeInfo((prev: Record<string, any>) => {
        return {
          ...prev,
          searchValueLeft: inputValue,
        };
      });
    }
    if (searchType == 'right') {
      setRightUserInfo((prev: Record<string, any>) => {
        return {
          ...prev,
          searchValueRight: inputValue,
        };
      });
    }
  };

  /** 处理树数据 */
  const handleLeftTree = (treeList: Record<string, any>[]) => {
    return treeList?.map((item) => {
      const titleTree = searchChangeColor(item?.text, leftTreeInfo?.searchValueLeft);
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
            id={item?.id + 'department'}
          >
            {getDeptPosTreeIcon(item?.textType)}
            &nbsp;
            {titleTree}
          </div>
        ),
        key: item?.id,
        children: item?.children?.length > 0 ? handleLeftTree(item?.children) : [],
        disabled: item?.textType == '2' ? false : true,
      };
    });
  };

  // 点击展开关闭树
  const onTreeExpand = (e) => {
    setLeftTreeInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        autoExpandParentLeft: false,
        expandedKeysLeft: e,
      };
    });
  };

  /**
   * 保存选中的值
   * @param checkedKeys
   * @param treeNodes
   */
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    const selectNode: Record<string, any> = treeNodes?.node;

    // 获取用户数据
    const userPayload = commonDeptGetUser([selectNode]);
    getUserRun(userPayload);

    if (checkedKeys && checkedKeys?.length > 0) {
      setLeftTreeInfo((prev: Record<string, any>) => {
        return {
          ...prev,
          selectKeysLeft: checkedKeys,
          selectNodeInfo: selectNode,
        };
      });
    }
  };

  // 点击搜索
  const onAutoSelectRight = (value: string, option: any) => {
    const optionId = option?.key;
    setRightUserInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        searchValueRight: value,
      };
    });

    setTimeout(() => {
      clickScrollToAnchor(optionId + 'userCardRight');
    }, 1000);
  };

  /** 人员选中  */
  const radioSelectUser = (radioID: string) => {
    const userInfo: Record<string, any> = getUserList?.find((item: any) => item?.id == radioID);
    setRightUserInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        selectRadioInfo: userInfo,
      };
    });
  };

  /** 处理合同编号 */
  const handCode = (info: Record<string, any>) => {
    let deptCode: string = `HL${info?.companyCode}${info?.departmentCode}`;

    return deptCode;
  };

  /** 保存 */
  const onSave = () => {
    if (rightUserInfo?.selectRadioInfo?.id) {
      const selectDeptInfo: Record<string, any> = leftTreeInfo?.selectNodeInfo?.attributes;
      if (!(selectDeptInfo?.companyID || selectDeptInfo?.departmentID)) {
        message.warning('当前选中岗位没有归属机构，请联系管理员！！！');
        return;
      }
      contractForm?.setFieldsValue({
        ownCompanyID: selectDeptInfo?.companyID || null,
        ownCompanyName: selectDeptInfo?.companyName || null,
        ownDepartmentID: selectDeptInfo?.departmentID || null,
        ownDepartmentName: selectDeptInfo?.departmentName || null,
        ownPositionID: leftTreeInfo?.selectNodeInfo?.id || null,
        ownPositionName: leftTreeInfo?.selectNodeInfo?.text || null,
        ownerID: rightUserInfo?.selectRadioInfo?.id || null,
        ownerName: rightUserInfo?.selectRadioInfo?.realName || null,

        createCompanyID: selectDeptInfo?.companyID || null,
        createDepartmentID: selectDeptInfo?.departmentID || null,
        createPositionID: leftTreeInfo?.selectNodeInfo?.id || null,
        createrID: rightUserInfo?.selectRadioInfo?.id || null,

        contractCode: `HL${selectDeptInfo?.companyCode}${selectDeptInfo?.departmentCode}`,
      });
      onCloseModalCommon(departmentRef);
    } else {
      message.error('请选择一位申请人！');
    }
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={departmentRef}
      title="选择申请人"
      onCancel={onClose}
      width={document.body.clientWidth * 0.65}
      bodyStyle={modalBodyStyle}
      onOk={onSave}
    >
      <Spin spinning={getFlowOrgTreeLoading || getUserLoading}>
        <div
          style={{
            width: '100%',
            height: '100%',
            padding: 5,
            overflow: 'hidden',
          }}
        >
          <Row className={`${styleFixCls}DepartmentSty`} gutter={[8, 0]}>
            <Col span={12}>
              <Card
                bordered
                className={`${styleFixCls}DepartmentSty-dataCardView`}
                title={
                  <>
                    <AutoComplete
                      style={{ width: '100%' }}
                      options={autoOptionLeft(getFlowOrgList, true)}
                      notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                      onSelect={onSelectAuto}
                    >
                      <Input
                        suffix={<SearchOutlined />}
                        onChange={(e) => {
                          onInputChange(e, 'left');
                        }}
                        placeholder="请按名称搜索"
                        allowClear
                      />
                    </AutoComplete>
                  </>
                }
              >
                <ScrollBarLayout
                  style={{
                    padding: '5px 10px',
                  }}
                >
                  {getFlowOrgList && getFlowOrgList?.length > 0 ? (
                    <Tree
                      treeData={handleLeftTree(getFlowOrgList)}
                      blockNode={true}
                      autoExpandParent={leftTreeInfo?.autoExpandParentLeft}
                      selectedKeys={leftTreeInfo?.selectKeysLeft}
                      onSelect={onTreeSelect}
                      expandedKeys={leftTreeInfo?.expandedKeysLeft}
                      onExpand={onTreeExpand}
                    />
                  ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                </ScrollBarLayout>
              </Card>
            </Col>
            <Col span={12}>
              <Card
                className={`${styleFixCls}DepartmentSty-dataCardView`}
                bordered
                title={
                  <>
                    <Row style={{ display: 'flex', alignItems: 'center' }}>
                      <Col span={8}>已选： {rightUserInfo?.selectRadioInfo?.id ? 1 : 0} / 1</Col>
                      <Col span={16}>
                        <AutoComplete
                          style={{ width: '100%' }}
                          options={autoOptionLeft(getUserList, false)}
                          notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                          onSelect={onAutoSelectRight}
                        >
                          <Input
                            suffix={<SearchOutlined />}
                            onChange={(e) => {
                              onInputChange(e, 'right');
                            }}
                            placeholder="请按名称搜索"
                            allowClear={true}
                          />
                        </AutoComplete>
                      </Col>
                    </Row>
                  </>
                }
              >
                <ScrollBarLayout
                  style={{
                    padding: '5px 10px',
                  }}
                >
                  {getUserList && getUserList.length > 0 ? (
                    <Radio.Group
                      style={{ width: '100%' }}
                      onChange={(e) => {
                        e?.stopPropagation();
                        radioSelectUser(e?.target?.value);
                      }}
                      value={rightUserInfo?.selectRadioInfo?.id}
                    >
                      {getUserList.map((item: any) => {
                        const titleNode = searchChangeColor(item?.realName, rightUserInfo?.searchValueRight);
                        return (
                          <div
                            id={item?.id + 'userCardRight'}
                            key={item?.id + 'userCardRight'}
                            className={`${styleFixCls}DepartmentSty-rightChild`}
                            onClick={(e) => {
                              e?.stopPropagation();
                              radioSelectUser(item?.id);
                            }}
                          >
                            <Radio value={item?.id}>{titleNode ?? '--'}</Radio>
                          </div>
                        );
                      })}
                    </Radio.Group>
                  ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                </ScrollBarLayout>
              </Card>
            </Col>
          </Row>
        </div>
      </Spin>
    </OneModal>
  );
};
